package edu.pku.sei.transformation.editor.controller.commands.node;

import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.transformation.editor.model.Rule;
import edu.pku.sei.transformation.editor.model.expression.Expression;
import edu.pku.sei.transformation.editor.model.variable.ObjectVariable;

public class ExpressionCreateCommand extends Command {
	private Expression expression;
	private MetaModelElement father;
	private int index = -1;

	public ExpressionCreateCommand(Expression exp, MetaModelElement obj,
			int index) {
		this.expression = exp;
		this.father = obj;
		this.index = index;
	}

	@Override
	public boolean canExecute() {
		if (expression == null || father == null)
			return false;
		else
			return super.canExecute();
	}

	@Override
	public void execute() {
		if (father instanceof ObjectVariable) {
			ObjectVariable obj = (ObjectVariable) father;
			if (index < 0 || index > obj.getExpressions().size())
				obj.getExpressions().add(expression);
			else
				obj.getExpressions().add(index, expression);
		} else if (father instanceof Rule) {
			Rule r = (Rule) father;
			if (index < 0 || index > r.getBody().size())
				r.getBody().add(expression);
			else
				r.getBody().add(index, expression);
		}
		expression.setContext(father);
	}

	@Override
	public void undo() {
		if (father instanceof ObjectVariable) {
			ObjectVariable obj = (ObjectVariable) father;
			obj.getExpressions().remove(expression);
		} else if (father instanceof Rule) {
			Rule r = (Rule) father;
			r.getBody().remove(expression);
		}
	}
}
